package com.teaching.management.controller.api;

import com.teaching.management.entity.Course;
import com.teaching.management.entity.CourseSelection;
import com.teaching.management.entity.Student;
import com.teaching.management.entity.User;
import com.teaching.management.repository.CourseRepository;
import com.teaching.management.repository.CourseSelectionRepository;
import com.teaching.management.repository.StudentRepository;
import com.teaching.management.repository.UserRepository;
import com.teaching.management.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 学生端相关的REST API
 */
@RestController
@RequestMapping("/api/student")
public class StudentRestController {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private CourseSelectionRepository courseSelectionRepository;

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取学生信息
     */
    @GetMapping("/info")
    public ResponseEntity<?> getStudentInfo(HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        return ResponseEntity.ok(student);
    }

    /**
     * 获取学生已选课程
     */
    @GetMapping("/courses/selected")
    public ResponseEntity<?> getSelectedCourses(HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        // 获取学生已选课程
        List<CourseSelection> selections = courseSelectionRepository.findByStudentId(student.getStudentId());
        return ResponseEntity.ok(selections);
    }

    /**
     * 获取可选课程
     */
    @GetMapping("/courses/available")
    public ResponseEntity<?> getAvailableCourses(
            @RequestParam(value = "semester", required = false) String semester,
            @RequestParam(value = "courseType", required = false) String courseType,
            @RequestParam(value = "keyword", required = false) String keyword,
            HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        // 创建查询条件
        Course example = new Course();
        if (semester != null && !semester.equals("all") && !semester.isEmpty()) {
            example.setSemester(semester);
        }
        if (courseType != null && !courseType.equals("all") && !courseType.isEmpty()) {
            example.setCourseType(courseType);
        }

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("semester", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("courseType", ExampleMatcher.GenericPropertyMatchers.exact());

        if (keyword != null && !keyword.isEmpty()) {
            matcher = matcher.withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase())
                    .withMatcher("courseId", ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase());
        }

        // 获取所有符合条件的课程
        List<Course> allCourses = courseRepository.findAll(Example.of(example, matcher));

        // 获取学生已选课程ID列表
        List<String> selectedCourseIds = courseSelectionRepository.findByStudentId(student.getStudentId())
                .stream()
                .map(CourseSelection::getCourseId)
                .collect(Collectors.toList());

        // 为课程添加状态标记（已选/可选）
        List<Map<String, Object>> coursesWithStatus = allCourses.stream().map(course -> {
            Map<String, Object> courseWithStatus = new HashMap<>();
            courseWithStatus.put("course", course);
            courseWithStatus.put("status", selectedCourseIds.contains(course.getCourseId()) ? "selected" : "open");
            return courseWithStatus;
        }).collect(Collectors.toList());

        return ResponseEntity.ok(coursesWithStatus);
    }

    /**
     * 选课
     */
    @PostMapping("/courses/select/{courseId}")
    public ResponseEntity<?> selectCourse(@PathVariable String courseId, HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        // 检查课程是否存在
        if (!courseRepository.existsById(courseId)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("课程不存在");
        }

        // 检查是否已经选过该课程
        CourseSelection example = new CourseSelection();
        example.setStudentId(student.getStudentId());
        example.setCourseId(courseId);
        if (courseSelectionRepository.exists(Example.of(example))) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("已经选过该课程");
        }

        // 创建选课记录
        CourseSelection selection = new CourseSelection();
        selection.setStudentId(student.getStudentId());
        selection.setCourseId(courseId);
        selection.setStatus("正在修");

        // 获取当前年份
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        selection.setYear(currentYear);

        // 设置学期
        selection.setSemester(student.getGrade());

        CourseSelection savedSelection = courseSelectionRepository.save(selection);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedSelection);
    }

    /**
     * 退选
     */
    @DeleteMapping("/courses/unselect/{courseId}")
    public ResponseEntity<?> unselectCourse(@PathVariable String courseId, HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        // 查找选课记录
        CourseSelection example = new CourseSelection();
        example.setStudentId(student.getStudentId());
        example.setCourseId(courseId);

        Optional<CourseSelection> selection = courseSelectionRepository.findOne(Example.of(example));
        if (selection.isEmpty()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未选择该课程");
        }

        // 检查是否可以退选（已有成绩的课程不能退选）
        CourseSelection courseSelection = selection.get();
        if (courseSelection.getScore() != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("已有成绩的课程不能退选");
        }

        // 删除选课记录
        courseSelectionRepository.delete(courseSelection);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取学生课表
     */
    @GetMapping("/schedule")
    public ResponseEntity<?> getSchedule(
            @RequestParam(value = "semester", required = false) String semester,
            HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        // 设置默认学期为当前学期
        if (semester == null || semester.isEmpty()) {
            semester = student.getGrade();
        }

        // 获取指定学期的选课记录
        List<CourseSelection> selections = courseSelectionRepository.findByStudentIdAndSemester(student.getStudentId(),
                semester);

        // 获取课程详情并组织为课表格式
        List<Map<String, Object>> scheduleItems = selections.stream().map(selection -> {
            Map<String, Object> item = new HashMap<>();

            // 获取课程信息
            courseRepository.findById(selection.getCourseId()).ifPresent(course -> {
                item.put("courseId", course.getCourseId());
                item.put("courseName", course.getName());
                item.put("credit", course.getCredit());
                item.put("teacherId", course.getTeacherId());
                item.put("classroomId", course.getClassroomId());
                item.put("courseType", course.getCourseType());
                item.put("semester", course.getSemester());
                item.put("period_id", course.getPeriodId());

                // 添加新的时间和地点信息
                item.put("class_day", course.getClassDay());
                if (course.getStartTime() != null) {
                    item.put("start_time", course.getStartTime().toString());
                }
                if (course.getEndTime() != null) {
                    item.put("end_time", course.getEndTime().toString());
                }
                item.put("weeks", course.getWeeks());
                item.put("location_detail", course.getLocationDetail());

                // 将这些字段添加到返回结果中
                item.put("selectionId", selection.getSelectionId());
                item.put("status", selection.getStatus());
                item.put("score", selection.getScore());

                // 添加教师姓名（如果可用）
                if (course.getTeacher() != null) {
                    item.put("teacherName", course.getTeacher().getName());
                }
            });

            return item;
        }).collect(Collectors.toList());

        return ResponseEntity.ok(scheduleItems);
    }

    /**
     * 获取学生成绩
     */
    @GetMapping("/grades")
    public ResponseEntity<?> getGrades(HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        // 获取学生所有选课记录
        List<CourseSelection> selections = courseSelectionRepository.findByStudentId(student.getStudentId());

        // 获取课程详情并添加到成绩记录中
        List<Map<String, Object>> gradesWithCourseInfo = selections.stream().map(selection -> {
            Map<String, Object> gradeInfo = new HashMap<>();

            // 添加选课信息
            gradeInfo.put("selectionId", selection.getSelectionId());
            gradeInfo.put("studentId", selection.getStudentId());
            gradeInfo.put("courseId", selection.getCourseId());
            gradeInfo.put("status", selection.getStatus());
            gradeInfo.put("score", selection.getScore());
            gradeInfo.put("year", selection.getYear());
            gradeInfo.put("semester", selection.getSemester());

            // 获取课程信息
            courseRepository.findById(selection.getCourseId()).ifPresent(course -> {
                gradeInfo.put("courseName", course.getName());
                gradeInfo.put("credit", course.getCredit());
                gradeInfo.put("teacherId", course.getTeacherId());
                gradeInfo.put("courseType", course.getCourseType());
            });

            return gradeInfo;
        }).collect(Collectors.toList());

        return ResponseEntity.ok(gradesWithCourseInfo);
    }

    /**
     * 更新学生基本信息
     */
    @PutMapping("/update")
    public ResponseEntity<?> updateStudentInfo(
            @RequestBody Map<String, Object> updatedInfo,
            HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 获取学生信息
        Student student = studentService.getStudentByUserId(user.getUserId());
        if (student == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生信息不存在");
        }

        try {
            // 更新学生基本信息
            if (updatedInfo.containsKey("name")) {
                student.setName((String) updatedInfo.get("name"));
            }
            if (updatedInfo.containsKey("gender")) {
                student.setGender((String) updatedInfo.get("gender"));
            }
            if (updatedInfo.containsKey("birthDate")) {
                String birthDateStr = (String) updatedInfo.get("birthDate");
                student.setBirthDate(java.sql.Date.valueOf(birthDateStr));
            }

            // 保存更新后的学生信息
            Student updatedStudent = studentRepository.save(student);

            // 如果需要更新用户名
            if (updatedInfo.containsKey("username")) {
                String newUsername = (String) updatedInfo.get("username");

                // 检查新用户名是否已被其他用户使用
                User existingUser = userRepository.findByUsername(newUsername);
                if (existingUser != null && !existingUser.getUserId().equals(user.getUserId())) {
                    return ResponseEntity.status(HttpStatus.CONFLICT).body("用户名已被使用");
                }

                // 更新用户名
                user.setUsername(newUsername);
                userRepository.save(user);
            }

            return ResponseEntity.ok(updatedStudent);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取课程详情
     */
    @GetMapping("/course/{courseId}")
    public ResponseEntity<?> getCourseDetail(@PathVariable String courseId, HttpSession session) {
        // 验证用户是否是学生
        User user = (User) session.getAttribute("user");
        if (user == null || !"学生".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 查找课程
        Optional<Course> courseOpt = courseRepository.findById(courseId);
        if (courseOpt.isEmpty()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("课程不存在");
        }

        return ResponseEntity.ok(courseOpt.get());
    }
}